/*****************************************************
** Author:
** Date: 2019-11-04
*
*****************************************************/

#include "uart.h"
#include "dnalua.h"

/**
 * @brief
 * @param  None
 * @retval None
 */
static int lua_uart_write(lua_State* l)
{
    int i, type, outsize;
    unsigned char output[256];

    // input table, output none
    print_lua_stack(l, "uart_write enter");

    if ((type = lua_type(l, -1)) != LUA_TTABLE) {
        lua_log_wrn("stack(%d) type %s err", -1, lua_typename(l, type));
        return 0;   
    }

    lua_log_dbg("get table(%d):", -1);
    for (i = 1; (type = lua_rawgeti(l, -1, i)) != 0; ++i) {
        // print_lua_stack(l);
        // lua_log_dbg("[%d] type %s 0x%x", i, \
        //             lua_typename(l, type), lua_tointeger(l, -1));
        output[i-1] = lua_tointeger(l, -1);
        lua_pop(l, 1);
    }
    outsize = i - 1;
    lua_log_dbg("output size %d", outsize);
    if (outsize >= sizeof(output)) {
        lua_log_wrn("output size %d excced %d", outsize, sizeof(output));
        outsize = sizeof(output);
    }
    lua_pop(l, 1);

    lua_arch_data_output(PORT_ID_UART, output, outsize);
    print_lua_stack(l, "uart_write exit");
    return 0;
}

int luaopen_uart(lua_State* l)
{
    const char *lib_name = "uart";
    luaL_Reg uart[] = {
        {"write",   lua_uart_write},
        {NULL, NULL}
    };
    luaL_openlib(l, lib_name, uart, 0);
    print_lua_stack(l, "open lua 'uart'");

    lua_log_inf("open lua 'uart' success");
    return LUA_ARCH_OK;
}

int luaclose_uart(lua_State* l)
{
    lua_log_inf("close lua 'uart'");
    return LUA_ARCH_OK;
}

/* End of file */



